package com.bestv.bsr.core.utils;


import com.bestv.bsr.core.constants.ServiceCodeEnum;
import com.bestv.bsr.core.exceptions.ValidateException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author taojiacheng
 */
public class ValidateUtils {

    final static Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * controller 校验参数
     */
    public static void validated(Object... args) {
        for (Object arg : args) {
            Set<ConstraintViolation<Object>> constraintViolations = VALIDATOR.validate(arg);
            for (ConstraintViolation<Object> valid : constraintViolations) {
                String message = valid.getMessage();
                if (message.startsWith("#")) {
                    String template = message.substring(1);
                    ServiceCodeEnum serviceCodeEnum = ServiceCodeEnum.getByCode(Integer.parseInt(template));
                    throw new ValidateException(serviceCodeEnum);
                } else {
                    throw new ValidateException(ServiceCodeEnum.PARAMETER_INVALID.getCode(),
                            valid.getPropertyPath().toString() + valid.getMessage());
                }
            }
        }
    }
}